﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public static partial class I18N
{
        private static I18NLanguageType systemlanguage = I18NLanguageType.ZhChs;
        private static LinkedList<Action> actionlist = new LinkedList<Action>();
		//private static Dictionary<string, Dictionary<ConfigLanguageType, string>> txtLanguageMap = new Dictionary<string, Dictionary<ConfigLanguageType, string>>();
		//private static ConfigLanguageType configLanguagetype = ConfigLanguageType.ZhChs;
		public static I18NLanguageType Language
		{
			get
			{
				if (systemlanguage == I18NLanguageType.Unknown)
				{
					systemlanguage = I18NLanguageType.En;
					//configLanguagetype = (ConfigLanguageType)Enum.Parse(typeof(ConfigLanguageType), systemlanguage.ToString());
			}
				return systemlanguage;
			}
			set
			{
				if (systemlanguage != value)
				{
					systemlanguage = value;
					//configLanguagetype = (ConfigLanguageType)Enum.Parse(typeof(ConfigLanguageType), systemlanguage.ToString());
					TranslateLanguage();
				}
			}
		}
		/// <summary>
		/// 注册语言切换事件
		/// </summary>
		public static LinkedListNode<Action> ListenLanguageChanged(Action action)
		{
			return actionlist.AddLast(action);
		}
		/// <summary>
		/// 撤销
		/// </summary>
		public static void UnlistenLanguageChanged(LinkedListNode<Action> handle)
		{
			actionlist.Remove(handle);
		}

		private static void TranslateLanguage()
        {
			if (Application.isPlaying)
			{
				LoadTextAsset();
			}
			else
			{
#if UNITY_EDITOR
				LoadTextAsset();
#endif
			}
		}

		private static void LoadTextAsset()
		{
			ExcuteTranslate();
		}

		private static void ExcuteTranslate()
        {
			LinkedListNode<Action> next;
			for (LinkedListNode<Action> linkedListNode = actionlist.First; linkedListNode != null; linkedListNode = next)
			{
				next = linkedListNode.Next;
				Action value = linkedListNode.Value;
				try
				{
					value();
				}
				catch (Exception ex)
				{
					Debug.LogError(ex.ToString());
				}
        }
		}

	#region Cache
	public static void SaveLanguage(I18NLanguageType language)
	{
		PlayerPrefs.SetInt("Language", (int)language);
	}

	public static I18NLanguageType ReadLanguage()
	{
		int index = PlayerPrefs.GetInt("Language", 0);
		return (I18NLanguageType)index;
	}

	#endregion



}


